package com.dream.filter;


import com.dream.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter("*.jsp")
public class JspFilter implements Filter {

   static List<String> no_interceptors=new ArrayList<String>();

    static {
        no_interceptors.add("/");
        no_interceptors.add("/login.jsp");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String requestURI = request.getRequestURI();
        HttpSession session = request.getSession();
        User loginUser= (User) session.getAttribute("loginUser");
        if(loginUser!=null){
            filterChain.doFilter(request,response);
        }else{
            if(no_interceptors.contains(requestURI)){
                filterChain.doFilter(request,response);
            }else{
                response.sendRedirect("/login.jsp");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
